const { get } = require('../../utils/request');
const { formatDate } = require('../../utils/util');

Page({
  data: {
    startDate: '',
    endDate: '',
    records: [],
    stats: {
      totalCount: 0,
      avgDuration: '0.0',
      avgQuality: '暂无'
    },
    page: 1,
    pageSize: 20,
    hasMore: true,
    isLoading: false
  },

  onLoad() {
    // 设置默认日期范围为最近一周
    const end = new Date();
    const start = new Date();
    start.setDate(start.getDate() - 7);
    
    this.setData({
      endDate: formatDate(end),
      startDate: formatDate(start)
    });

    this.loadRecords();
  },

  onStartDateChange(e) {
    this.setData({
      startDate: e.detail.value,
      page: 1,
      records: [],
      hasMore: true
    });
    this.loadRecords();
  },

  onEndDateChange(e) {
    this.setData({
      endDate: e.detail.value,
      page: 1,
      records: [],
      hasMore: true
    });
    this.loadRecords();
  },

  // 计算统计数据
  calculateStats(records) {
    if (!records || records.length === 0) {
      return {
        totalCount: 0,
        avgDuration: '0.0',
        avgQuality: '暂无'
      };
    }

    const totalCount = records.length;
    
    // 计算平均时长
    const totalDuration = records.reduce((sum, record) => {
      const duration = parseFloat(record.duration) || 0;
      return sum + duration;
    }, 0);
    const avgDuration = (totalDuration / totalCount).toFixed(1);

    // 计算平均质量
    const qualityMap = {
      '很好': 4,
      '良好': 3,
      '一般': 2,
      '较差': 1
    };
    const qualitySum = records.reduce((sum, record) => sum + qualityMap[record.quality], 0);
    const avgQualityScore = qualitySum / totalCount;
    let avgQuality = '一般';
    if (avgQualityScore >= 3.5) avgQuality = '很好';
    else if (avgQualityScore >= 2.5) avgQuality = '良好';
    else if (avgQualityScore >= 1.5) avgQuality = '一般';
    else avgQuality = '较差';

    return {
      totalCount,
      avgDuration,
      avgQuality
    };
  },

  async loadRecords() {
    if (this.data.isLoading || !this.data.hasMore) return;

    try {
      this.setData({ isLoading: true });

      const params = {
        page: this.data.page,
        pageSize: this.data.pageSize,
        startDate: this.data.startDate,
        endDate: this.data.endDate
      };

      const res = await get('/records/sleep', params);
      
      // 格式化记录数据
      const formattedRecords = res.records.map(record => ({
        ...record,
        duration: record.duration ? (record.duration / 60).toFixed(1) : '0.0' // 转换为小时并处理空值
      }));

      const newRecords = this.data.page === 1 ? 
        formattedRecords : 
        [...this.data.records, ...formattedRecords];

      this.setData({
        records: newRecords,
        hasMore: formattedRecords.length === this.data.pageSize,
        page: this.data.page + 1,
        stats: this.calculateStats(newRecords),
        isLoading: false
      });
    } catch (error) {
      console.error('加载睡眠记录失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
      this.setData({ isLoading: false });
    }
  },

  loadMore() {
    this.loadRecords();
  },

  onPullDownRefresh() {
    this.setData({
      page: 1,
      records: [],
      hasMore: true
    });
    this.loadRecords().then(() => {
      wx.stopPullDownRefresh();
    });
  },

  onReachBottom() {
    if (this.data.hasMore) {
      this.loadMore();
    }
  }
}); 